<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\Admin;
use app\madmin\model\Merchant;
use app\madmin\model\Role;
use app\madmin\model\Rule;
use app\utils\TrimData;
use think\db\exception\PDOException;
use think\db\Query;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\model\Relation;
use app\utils\Addons;
use app\utils\Receipts;

class OperationService
{

    /**
     * 校验登录信息
     * @param string $ip
     * @param string $username
     * @param string $password
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function check(string $ip, string $username, string $password)
    {

        $admin = Admin::withoutGlobalScope(['mallId'])
            ->where('status', 1)
            ->getByUsername($username);

        if (!$admin || hash('sha256', $password) !== $admin->password)
            return [HTTP_NOTACCEPT, '账号或密码错误'];

        $verification = request()->header('Verification');
        if ($verification) {
            $check = Addons::check($admin->mall_id, 29);
            if (!$check) {
                return [HTTP_NOTACCEPT, '请先激活插件'];
            }
        }

//        $typeIndate = Db::table('jiecheng_lessee')
//            ->where(['status' =>1])
//            ->field('type,indate')
//            ->whereNull("delete_time")
//            ->find($admin->mall_id);
//        if (!$typeIndate){
//            return [HTTP_NOTACCEPT, '商城已禁用'];
//        }
//        if ($typeIndate['type'] === 0 && (empty($typeIndate['indate']) || strtotime($typeIndate['indate']) < time())){
//            return [HTTP_NOTACCEPT, '商城已过期，请续费'];
//        }

        unset($admin->password);
        $admin->login_ip = $ip;
        global $token;

        $token = "mall_" . createToken();
        $admin->ac_token = $token;
        $admin->save();

        //mall端rule
        global $user;
        $user = $admin;
        if ($admin['is_root'] == 1) {
            $rule = Rule::where('status', 1)->select();
        } else {
            $rule = $admin->role->rule()->where('rule.status', 1)->select();
        }
        $ruleIds = array_column($rule->toArray(), 'id');


//        $addonsService = new AddonsService();
//        list($code, $addons_list) = $addonsService->list();
//        $is_not_active_addons = [];
//        foreach ($addons_list as $addons) {
//            if (!$addons['is_active']) {
//                $is_not_active_addons[] = $addons['id'];
//            }
//        }

        $ruleList = Rule::with([
            'ruleExtend' => function (Relation $query) {
                return $query->visible(['rule_route', 'method']);
            }
        ])->where(['id' => $ruleIds])
//            ->where('up', "not in", $is_not_active_addons)
            ->visible(['resource', 'level'])
            ->select();


//        //shop端rule
//        $shopRuleIds = MallShopRule::where('role_id', $admin->role->id)->value('rule_list');
//        if ($shopRuleIds)
//            $shopRuleIds = json_decode($shopRuleIds, true);
//
//        $shopRuleList = shopRule::with(
//            [
//                'rule_extend' => function (Query $query) {
//                    $query->visible(['rule_route', 'method']);
//                }
//            ])->where(['id' => $shopRuleIds])
//            ->visible(['id', 'resource'])
//            ->select();
//
//        $shopData = $shopRuleList === null ? [] : $this->clearRule($shopRuleList->toArray());

        $admin->affiliation = "mall";

        $merchant = Merchant::where(['is_self' => 1])->field('id')->find();

        $admin->merchant_id = $merchant->id;
        $admin->is_self = 1;
        $admin->flag = true;
        $admin->audit_type = 1;

        $admin->merchant_merchant_id = $merchant->id;
        $admin->used_affiliation = 'mall';

        //token数据存入缓存
        //归属
        Cache::store('redis')->set("mall_token:" . $token, $admin, 60 * 60 * 24 * 30);
        $shopToken = "shop_" . createToken();

        (new Receipts())->remote();
        //归属
        $admin->affiliation = "shop";
        Cache::store('redis')->set("shop_token:" . $shopToken, $admin, 60 * 60 * 24 * 30);

        $site = Db::table('jiecheng_lessee')->where('id', $admin->mall_id)->value("site");

        $msg = [
            "user" => $admin,
            "site" => $site
        ];

        return [HTTP_SUCCESS,
            [
                'msg' => $msg,
                'token' => $admin->ac_token,
                'shop_token' => $shopToken,
                'ruleList' => $ruleList,
            ]
        ];
    }


    /**
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {
        $admin = Admin::field('id,username,avatar,name,mobile,role_id,is_root,status,create_time,update_time')
            ->with('role');
        $admin = TrimData::searchDataTrim($admin, $data, ['name', 'mobile', 'begin_date', 'end_date']);

        $list = $admin->where($data)
            ->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * @param array $data
     * @return array
     */
    public function save(array $data)
    {
        $data['login_ip'] = getIp();
        $is_root = Role::where('id', $data['role_id'])->value('is_root');
        if ($is_root == 1) {
            throw new \PDOException('超级管理员已存在！', HTTP_INVALID);
        }
        try {
            $admin = Admin::create($data);
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), "Index_username") !== false) {
                throw new \PDOException('账号已存在', HTTP_INVALID);
            }

            if (strpos($e->getMessage(), "Index_mobile") !== false) {
                throw new \PDOException('手机号已存在', HTTP_INVALID);
            }
        }
        return [HTTP_CREATED, $admin];
    }

    public function read(int $id)
    {
        $model = Admin::find($id);
        if ($model) {
            unset($model->password);
            unset($model->ac_token);
        }
        return [HTTP_SUCCESS, $model];
    }

    private function getAdmin($id)
    {
        $admin = admin::find($id);
        if (1 === $admin->is_root) {
            return true;
        }
        return false;
    }


    public function update(int $id, array $data)
    {
        $update_time = $data['update_time'];
        unset($data['update_time']);
        $is_root = $this->getAdmin($id);
        $role = Role::where('id', $data['role_id'])->value('is_root');
        if (!$is_root && $role == 1) {
            throw new \PDOException('超级管理员已存在！', HTTP_INVALID);
        }
        try {
            $admin = Admin::update($data, ['id' => $id, 'update_time' => $update_time]);
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), "Index_username") !== false) {
                throw new \PDOException('账号已存在', HTTP_INVALID);
            }
        }
        return [HTTP_CREATED, $admin];
    }

    public function delete($id)
    {
        if ($this->getAdmin($id)) {
            throw new Exception("初始账号不能操作", HTTP_NOTACCEPT);
        }
        Admin::destroy(function ($query) use ($id) {
            $query->where(['id' => $id, 'is_root' => 0]);
        });
        return HTTP_NOCONTEND;
    }


    public function scopeSearch(Query $query, array $data)
    {
        $data = array_filter($data, static function ($val) {
            return is_array($val) || (is_string($val) && "" !== trim($val));
        });
        $query->alias("a")
            ->join("order_info b", "a.order_info_id = b.id", 'left')
            ->join("think_member c", "a.user_id = c.id")
            ->field("a.*,b.name,b.tel,c.username");
        foreach ($data as $k => $v) {
            if ($k === 'create_time' || $k === 'update_time') {
                if (!empty($v['begin']) && !empty($v['end'])) {
                    $query->whereTime("a." . $k, "between", [$v['begin'], $v['end']]);
                } elseif (!empty($v['begin'])) {
                    $query->whereTime("a." . $k, ">=", $v['begin']);
                } elseif (!empty($v['end'])) {
                    $query->whereTime("a." . $k, "<=", $v['end']);
                }
            } elseif ($k === 'username') {
                $query->where("c." . $k, 'like', "%$v%");
            } elseif ($k === "name") {
                $query->where("b." . $k, 'like', "%$v%");
            } elseif ($k === "order_num") {
                $query->where("a." . $k, 'like', "%$v%");
            } elseif ($k === "tel") {
                $query->where("b." . $k, $v);
            } else {
                $query->where("a." . $k, $v);
            }
        }
        return $query;

    }

    /**修改自身数据
     * @param int $id
     * @param array $data
     * @return array
     * @throws Exception
     */
    public function selfUp(int $id, array $data)
    {
        global $user;
        $where[] = ['id', '=', $id];
        if (isset($data['old_password'])) $where[] = ['password', '=', hash('sha256', $data['old_password'])];
        $admin = Admin::where($where)->find();
        if (isset($data['password']) && !isset($data['old_password'])) throw new Exception('修改密码必须提交原密码!', HTTP_INVALID);
        if (!isset($data['password']) && isset($data['old_password'])) throw new Exception('未提交新密码!', HTTP_INVALID);
        if (empty($admin)) throw new Exception('旧密码输入有误!', HTTP_INVALID);
        if ($id != $user->id) throw new Exception('无权修改他人数据!', HTTP_INVALID);
        if (isset($data['password'])) {
            $password = $data['password'];
            unset($data['old_password'], $data['password']);
            $data['password'] = hash('sha256', $password);
        }
        Admin::update($data, ['id' => $id], ['password', 'name', 'avatar', "mobile"]);
        return [HTTP_CREATED, "成功!"];
    }

}
